<?php


namespace app\api\service;


use GuzzleHttp\Client;
use think\Db;
use think\Log;

/**
 * 封装微信的公众号的access_token的查询相关
 * Class WechatInfoService
 * @package app\api\service
 */
class WechatInfoService
{

    /**
     * 根据appid 从数据库里面获取access_token
     * @param $appId
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAccessToken($appId){

        $res = Db::name('wx_chart')->where('appid', $appId)->find();
        if(empty($res)){
            throw new \Exception("没有查询到{$appId}对应的access_token");
        }

        return $res['access_token'];
    }



    /**
     * 根据appid 从数据库里面获取access_token
     * @param $appId
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAccessTokenIncludeJs($appId){

        $res = Db::name('wx_chart')->where('appid', $appId)->find();
        if(empty($res)){
            throw new \Exception("没有查询到{$appId}对应的access_token");
        }
        $result['access_token'] = $res['access_token'];
        $result['jsapi_ticket'] = $res['jsapi_ticket'];
        $result['secret'] = $res['secret'];
        $result['appid'] = $res['appid'];
        return $result;
    }


    /**
     * 获取微信的openid
     * @param $appId
     * @param $code
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getWechatOpenId($appId, $code){

        try{

            Log::info("传入的code值为{$code}");

            $token = $this->getAccessTokenIncludeJs($appId);

            $secret = $token['secret'];

            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";

            $url = sprintf($url, $appId, $secret, $code);

            $client= new Client(['timeout'=>10, 'http_errors'=>false]);

            $res = $client->request('GET', $url);

            $body = $res->getBody()->getContents();

            Log::info("接口返回的内容{$body}");

            if($res->getStatusCode() != 200){

                throwBusinessException($res->getBody()->getContents());

            }else{
                $bodyJson = json_decode($body, true);

                $openId = isset($bodyJson['openid']) ? $bodyJson['openid'] : "";

                $redis = new \Redis();

                $rb = $redis->connect('127.0.0.1', 6379);
                if(!$rb){
                    Log::error("redis链接失败");
                }
                if($rb) {

                    if (empty($openId)) {

                        $openId = $redis->get("code:generate:openid" . $code);
                    } else {
                        $redis->set("code:generate:openid" . $code, $openId);
                    }
                    $redis->close();
                }
                return $openId;

            }

        }catch (\Exception $e){
            Log::error($e->getMessage());
        }
    }



}